package art.yulang.utils;


import art.yulang.annotation.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component("connectionUtil")
public class ConnectionUtil {
    //存储当前线程的连接
    ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 从当前线程获取
     * @return
     */
    public Connection getCurrentThreadConnection() throws SQLException {
        //判断当前线程中是否有已经绑定的连接，有的话直接返回连接，没有得话则从连接池获取一个新的连接返回并绑定存储到当前线程
        Connection connection = threadLocal.get();
        if(connection == null){
            connection = DruidUtils.getInstance().getConnection();
            threadLocal.set(connection);
        }
        return  connection;
    }
}
